String.prototype.toDate = function() {

	return new Date(Date.parse(this.replace(/-/g, "/")));

}

Date.prototype.format = function(format) {
	var date = {
		"M+" : this.getMonth() + 1,
		"d+" : this.getDate(),
		"h+" : this.getHours(),
		"m+" : this.getMinutes(),
		"s+" : this.getSeconds(),
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		"S+" : this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '')
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k]
					: ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}

// 加载地图数据
function loadAreaData(bdMap) {
	var data = null;
	$.ajax({
		url : "/flight/loadAreaLable",
		async : false,
		success : function(dd) {
			data = dd;
		}
	});
	// map
	for (var i = 0; i < data.length; i++) {
		var city = new BMap.Marker(new BMap.Point(data[i].lng, data[i].lat), {
			icon : new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
				scale : 3,
				fillColor : '#E60000',
				fillOpacity : 1,
				strokeColor : '#fff',
				strokeWeight : 1
			// 线宽
			})
		});
		city.setTitle(data[i].city);
		city.setTop(false);

		var lable = new BMap.Label(data[i].city);
		lable.setStyle({
			color : "white",
			fontSize : "8px",
			textShadow : "2PX 2PX 2PX #000",
			backgroundColor : "rgba(0, 0, 0, 0)",
			border : '0'
		});
		lable.setOffset(new BMap.Size(13, -3));
		city.setLabel(lable);
		if (data[i].level != 1) {
			city.hide();
		}

		bdMap.addOverlay(city);
		// 设置全局变量数值
		GL_AREA_MAP.put(data[i].city, data[i]);
		GL_AREA_SYMBOL_MAP.put(data[i].city, city);
	}
}

// 显示数据
function showCity(obj) {
	var level = obj.prop('value');
	var checked = obj.is(':checked');
	GL_AREA_SYMBOL_MAP.each(function(key, value, index) {
		var dataLevel = GL_AREA_MAP.get(key).level;
		// console.log(dataLevel);
		if (dataLevel == level) {
			if (checked) {// 已经点击过的再点击，则隐藏
				value.show();
			} else {
				value.hide();
			}
		}
	});
}

// 航班列表
function FlightListControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	this.defaultOffset = new BMap.Size(30, 30);
}
FlightListControl.prototype = new BMap.Control();
FlightListControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class=" control-panel-row"><h4>航班列表</h4></div>'
			+ '<div id="flights"></div>';
	// 添加文字说明
	div.id = 'flightList';
	div.className = 'row';
	div.innerHTML = tpl;
	div.style.cursor = "pointer";

	map.getContainer().appendChild(div);

	// 将DOM元素返回
	return div;
};

function loadFlightListAjax() {
	$.ajax({
		url : "/flight/loadFlightList",
		async : false,
		success : function(dd) {
			
			var tmp = '';
			if (dd.length == 0) {
				var tbody = $('#flights');
				tmp = '<div>查询不到航班信息</div>';
				tbody.append(tmp);
			} else {
				initData(dd);
				// 启动定时任务
				GL_GCTASK = setInterval(runUpdateTask, 5000);
			}

		}
	});
}

// 初始化数据
function initData(dd) {
	var tbody = $('#flights');
	var divContent = '';
	var tableHead = '<tr>     ' + '								<th>航班号</th>         '
			+ '								<th>线路</th>           ' + '								<th>起飞时间</th>       '
			+ '								<th>到达时间</th>       ' + '								<th>状态</th>          '
			+ '								<th>操作</th></tr>           ';

	for (var i = 0; i < dd.length; i++) {
		GL_PLANE_MAP.put(dd[i].flight_id, dd);
		var flyTime = dd[i].fly_time.toDate();
		var landTime = dd[i].land_time.toDate();
		var status = '';
		if (dd[i].status == 0) {// 待起飞
			status = '<font color="#ff6666">待起飞</font>';
		} else if (dd[i].status == 1) {// 飞行中
			status = '<font color="#0099cc">飞行中</font>';
		} else if (dd[i].status == 2) {// 降落
			status = '<font color="#99cc00">降落</font>';
		}

		divContent += '<tr>' + '<td onclick=clearPlainRunLine('
				+ dd[i].flight_id + ');>' + dd[i].flight_code + '</td>'
				+ '<td>' + dd[i].from_airport + ' 到 ' + dd[i].to_airport
				+ '</td>' + '<td>' + flyTime.format('MM-dd hh:mm') + '</td>'
				+ '<td>' + landTime.format('MM-dd hh:mm') + '</td>' + '<td>'
				+ status + '</td>' + '<td><a onclick="setPlainRunLine('
				+ dd[i].flight_id + ');"> <i class="fa fa-search" />轨迹</a>|'
				+ '<a onclick="showInfo(' + dd[i].flight_id
				+ ');"><i class="fa fa-table" />详情</a></td>' + '</tr>';

		if (i != 0 && (i + 1) % 5 == 0) {
			var style = 'style="display:none;"';
			if (GL_PLANE_LIST_IDX == 0) {
				style = '';
			}
			var tmp = tableHead + divContent;
			divContent = '<table class="control-panel-table" id=\"planeList_div_'
					+ GL_PLANE_LIST_IDX
					+ '\" '
					+ style
					+ '>'
					+ tmp
					+ '</table>';
			tbody.append(divContent);
			divContent = '';
			GL_PLANE_LIST_IDX++;
		}

		if ((i + 1) % 5 != 0 && i == dd.length - 1) {
			var style = 'style="display:none;"';
			var tmp = tableHead + divContent;
			divContent = '<table class="control-panel-table" id=\"planeList_div_'
					+ GL_PLANE_LIST_IDX
					+ '\" '
					+ style
					+ '>'
					+ tmp
					+ '</table>';
			tbody.append(divContent);
			divContent = '';
			GL_PLANE_LIST_IDX++;
		}

		// 初始化第一个航班的信息
		if (i == 0) {
			showInfo(dd[i].flight_id);
		}

		// 显示飞机坐标icon
		if (dd[i].position != null) {
			setPlainOnMap(dd[i]);
		}
		// 初始化航线对象,数据延迟加载
		initPlaneLine(dd[i].flight_id);
		// 登记信息采集任务
		GL_UPDATE_TASK_MAP.put(dd[i].flight_id);
	}
}

function refresh() {
	var GL_PLANE_MAP = new Map();// 飞机航班信息数据
	var GL_PLANE_SYMBOL_MAP = new Map();// 飞机MAP
	var GL_LINE_MAP = new Map();// 航线轨迹
	var GL_LINE_SHOW_MAP = new Map();// 航线轨迹展示记录
	var GL_UPDATE_TASK_MAP = new Map();// 定时任务清单

}

// 飞行信息
function showInfo(flightId) {
	$.ajax({
		url : "/flight/getFlightInfo",
		async : false,
		data : {
			"flight_id" : flightId
		},
		success : function(dd) {

			var tmp = '<font class="flight-code">' + dd.flight_code + '</font>'
					+ '<font class="font-blue">' + dd.from_airport + ' 到 '
					+ dd.to_airport + '</font><br/>';

			// 乘机人数
			tmp += '<font>乘机人数:' + (dd.people != null ? dd.people : 0)
					+ '人</font><br/>';
			// 飞行时间
			var time = '-';
			if (dd.plan_land_time != null && dd.fly_time != null) {
				time = timeInterval(dd.fly_time.toDate(), dd.plan_land_time
						.toDate());
				tmp += '<font>预计飞行时间:' + time + '</font><br/>';
			}

			// 预计到达时间
			var t = '-';
			if (dd.plan_land_time != null) {
				t = dd.plan_land_time.toDate().format('yyyy-MM-dd hh:mm');
				tmp += '<font>预计到达时间:' + t + '</font>';
			}

			var flightContent = $('#flightContent');
			flightContent.empty();
			flightContent.append(tmp);
		}
	});

}

function timeInterval(startTime, endTime) {
	var planFlyTime = endTime - startTime;
	console.log(planFlyTime);
	// 计算出相差天数
	var days = Math.floor(planFlyTime / (24 * 3600 * 1000));

	// 计算出小时数
	var leave1 = planFlyTime % (24 * 3600 * 1000);// 计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));

	// 计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));

	var time = '';
	if (days != 0) {
		time += days + '天 ';
	}
	time += hours + '小时 ' + minutes + '分钟';

	return time;
}

// 飞机信息面板切换
function marqueePlaneList() {
	// console.log(GL_PLANE_LIST_IDX+' '+GL_PLANE_MARQUE_IDX);
	if (GL_PLANE_MARQUE_IDX != (GL_PLANE_LIST_IDX - 1)) {
		var oldIdx = GL_PLANE_MARQUE_IDX;
		GL_PLANE_MARQUE_IDX++;
		$('#planeList_div_' + oldIdx).hide();
		$('#planeList_div_' + GL_PLANE_MARQUE_IDX).fadeIn();
	} else {
		$('#planeList_div_' + GL_PLANE_MARQUE_IDX).hide();
		$('#planeList_div_0').fadeIn();
		GL_PLANE_MARQUE_IDX = 0;

	}
}

// 显示飞机
function setPlainOnMap(dd) {
	var pos = dd.position.split('|');
	var lng = pos[0];
	var lat = pos[1];
	var point = new BMap.Point(lng, lat);
	var _vectorPlane = new BMap.Marker(point, {
		// 初始化小飞机Symbol
		icon : new BMap.Symbol(BMap_Symbol_SHAPE_PLANE, {
			scale : 2,
			rotation : 135,
			fillColor : '#C6E2FF',
			fillOpacity : 1,
			strokeColor : '#555',
			strokeWeight : 1
		// 线宽
		})
	});

	// 设置飞机的title
	_vectorPlane.setTitle(dd.from_airport + '->' + dd.to_airport);

	// 飞机图标旋转角度
	var to_pos = dd.to_gps.split('|');
	var to_lng = to_pos[0];
	var to_lat = to_pos[1];
	var rotation = caluateRotation(lng, lat, to_lng, to_lat);
	if (rotation != 0) {// 返回值不为0时设置角度
		_vectorPlane.setRotation(rotation);
	}
	GL_PLANE_SYMBOL_MAP.put(dd.flight_id, _vectorPlane);
	map.addOverlay(_vectorPlane);
}

function initPlaneLine(flightId) {
	var points = [];
	var curve = new BMap.Polyline(points);
	curve.setStrokeColor('#1E90FF');
	curve.setStrokeWeight(3);
	curve.hide();
	map.addOverlay(curve);
	GL_LINE_MAP.put(flightId, curve);// 初始化时候登记航线数据

}

function showLine(flightId) {
	if (GL_LINE_SHOW_MAP.contain(flightId)) {
		GL_LINE_SHOW_MAP.remove(flightId);
		GL_LINE_MAP.get(flightId).hide();
	} else {
		GL_LINE_SHOW_MAP.put(flightId, 0);
		GL_LINE_MAP.get(flightId).show();
	}
}

// 设置飞机运行轨迹
function setPlainRunLine(flightId) {
	if (GL_LINE_MAP.contain(flightId)) {
		var points = getGPSRecord(flightId);
		if (points != null && points.length > 0) {
			var line = GL_LINE_MAP.get(flightId);
			var tmp = [];
			for (var i = 0; i < points.length; i++) {
				tmp.push(new BMap.Point(points[i].lng, points[i].lat));
			}
			line.setPath(tmp);
			showLine(flightId);
		}
	} else {
		console.log('flightId=[' + flightId + '] is not in GL_LINE_MAP');
	}
}

function clearPlainRunLine(flightId) {
	var line = GL_LINE_MAP.get(flightId);
	line.hide();
}

// 获取飞机GPS轨迹
function getGPSRecord(flightId) {
	var myPoints = [];
	$.ajax({
		url : "/flight/getGPSRecord",
		async : false,
		data : {
			"flight_id" : flightId
		},
		success : function(dd) {
			myPoints = dd;
		}
	});
	return myPoints;
}

function caluateRotation(cur_lng, cur_lat, to_lng, to_lat) {
	var angle = Math.atan((to_lng - cur_lng) / (to_lat - cur_lat)) * 180
			/ Math.PI;
	if (!isNaN(angle)) {
		var rotation = 135 + Math.round(angle) - 90;
		return rotation;
	} else {
		return 0;
	}
}

// GPS定时采集任务
function runUpdateTask() {
	// 循环
	GL_UPDATE_TASK_MAP.each(function(key, value, index) {
		var points = getGPSRecord(key);
		var len = points.length;
		if (len > 0) {// 存在轨迹数据
			// 获取飞机坐标
			var curLocate = new BMap.Point(points[len - 1].lng,
					points[len - 1].lat);
			var planeIcon = GL_PLANE_SYMBOL_MAP.get(key);
			planeIcon.setPosition(curLocate);

			// 设置飞机旋转角度
			var planeInfo = GL_PLANE_MAP.get(key);
			var rot = caluateRotation(points[len - 1].lng, points[len - 1].lat,
					planeInfo.lng, planeInfo.lat);
			planeIcon.setRotation(rot);

			// 更新航线数据
			var line = GL_LINE_MAP.get(key);
			var tmp = [];
			for (var i = 0; i < points.length; i++) {
				tmp.push(new BMap.Point(points[i].lng, points[i].lat));
			}
			line.setPath(tmp);
			if (GL_LINE_SHOW_MAP.contain(key)) {// 存在等级则打开展示记录
				line.show();
			}
		}
		setTimeout(100);// 暂停100ms
	});

}

// 航班信息
function FlightInfoControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	this.defaultOffset = new BMap.Size(30, 300);
}

FlightInfoControl.prototype = new BMap.Control();

FlightInfoControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class="control-panel-row flightInfoTitle"><h4>航班信息</h4></div>'
			+ '<div id="flightInfoContainer"><div id="flightContent"></div></div>';
	// 添加文字说明
	div.id = 'flightInfo';
	div.className = 'box';
	div.innerHTML = tpl;
	// 设置样式
	div.style.cursor = "pointer";
	// div.style.border = "1px solid gray";

	map.getContainer().appendChild(div);
	// 将DOM元素返回
	return div;
}

function CityControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	this.defaultOffset = new BMap.Size(30, 30);
}

CityControl.prototype = new BMap.Control();

CityControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class="control-panel-row cityControlDiv">'
			+ '<div class="cityShowTitle"><a class="fa fa-plane"></a>显示城市座标</div>'
			+ '<div class="cityCheckBox"><input id="level1Citys"type="checkbox" value="1" >一级城市 '
			+ '<input type="checkbox" id="level2Citys" value="2">二级城市</div>'
			+ '</div>';
	// 添加文字说明
	div.id = 'cityControl';
	div.className = 'box';
	div.innerHTML = tpl;
	// 设置样式
	div.style.cursor = "pointer";
	map.getContainer().appendChild(div);
	// 将DOM元素返回
	return div;
}

var rDrag = {
	o : null,
	// 欢迎来到站长特效网，我们的网址是www.zzjs.net，很好记，zz站长，js就是js特效，本站收集大量高质量js代码，还有许多广告代码下载。
	init : function(o) {
		o.onmousedown = this.start;
	},
	start : function(e) {
		var o;
		e = rDrag.fixEvent(e);
		e.preventDefault && e.preventDefault();
		rDrag.o = o = this;
		o.x = e.clientX - rDrag.o.offsetLeft;
		o.y = e.clientY - rDrag.o.offsetTop;
		document.onmousemove = rDrag.move;
		document.onmouseup = rDrag.end;
	},
	move : function(e) {
		e = rDrag.fixEvent(e);
		var oLeft, oTop;
		oLeft = e.clientX - rDrag.o.x;
		oTop = e.clientY - rDrag.o.y;
		rDrag.o.style.left = oLeft + 'px';
		rDrag.o.style.top = oTop + 'px';
	},
	end : function(e) {
		e = rDrag.fixEvent(e);
		rDrag.o = document.onmousemove = document.onmouseup = null;
	},
	fixEvent : function(e) {
		if (!e) {
			e = window.event;
			e.target = e.srcElement;
			e.layerX = e.offsetX;
			e.layerY = e.offsetY;
		}
		return e;
	}
}
